<template>
  <div class="profile-container">
    <!-- 未登录提示 -->
    <div v-if="!authStore.isAuthenticated" class="error-message">
      请先登录以查看个人资料。
    </div>

    <!-- 加载中 -->
    <div v-else-if="loading" class="loading">加载中...</div>

    <!-- 用户信息展示与编辑 -->
    <div v-else-if="userInfo" class="profile-card animate__animated animate__fadeInUp">
      <h2 class="profile-title">我的资料</h2>

      <!-- 用户头像区域 -->
      <div class="avatar-section text-center">
        <img :src="avatarUrl || defaultAvatar" alt="用户头像" class="avatar-img" />
        <input type="file" accept="image/*" @change="uploadAvatar" class="avatar-input" />
        <p v-if="uploadStatus" class="upload-status">{{ uploadStatus }}</p>
      </div>

      <!-- 基本信息 -->
      <div class="info-grid">
        <div class="info-item">
          <label>用户名：</label>
          <span>{{ userInfo.username }}</span>
        </div>
        <div class="info-item">
          <label>用户ID：</label>
          <span>{{ userInfo.ID }}</span>
        </div>
        <div class="info-item">
          <label>用户等级：</label>
          <span class="level-tag">Lv.{{ userInfo.level }}</span>
        </div>
        <div class="info-item">
          <label>权限说明：</label>
          <span class="permission-desc">{{ permissionDescription }}</span>
        </div>
      </div>

      <!-- 可编辑信息 -->
      <el-form label-position="left" label-width="80px" class="edit-form">
        <el-form-item label="昵称">
          <el-input v-model.trim="userInfo.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model.trim="userInfo.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-button type="primary" @click="saveUserInfo" class="submit-button w-100">
          保存更改
        </el-button>
      </el-form>

      <!-- 注销按钮 -->
      <div class="logout-btn">
       <el-button type="danger" @click="authStore.logout">退出登录</el-button>
      </div>
    </div>

    <!-- 错误提示 -->
    <div v-else class="error-message">
      无法加载用户信息，请检查登录状态。
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted } from 'vue'
import axios from '../axios'
import { useAuthStore } from '../store/auth'
import { useRoute } from 'vue-router'

interface UserInfo {
  ID: number;
  username: string;
  password: string;
  avatar: string;
  birthday: string;
  gender: string;
  signature: string;
  level: number;
  exp: number;
  nickname?: string; // 可选字段，如果后端允许扩展
  email?: string;    // 同上
}

const userInfo = ref<UserInfo | null>(null)
const loading = ref(true)
const avatarUrl = ref<string | null>(null)
const uploadStatus = ref('')
const defaultAvatar = 'default-avatar.png'

const authStore = useAuthStore()
const route = useRoute()

// 获取当前用户ID或路由参数中的用户ID
// 获取用户信息
const fetchUserInfo = async () => {
  try {
    const response = await axios.get<UserInfo>('/api/users/me');
    userInfo.value = response.data;
    avatarUrl.value = response.data.avatar || defaultAvatar;
  } catch (error) {
    console.error('获取用户信息失败:', error);
    userInfo.value = null;
  } finally {
    loading.value = false;
  }
};
// 保存用户信息到后端
const saveUserInfo = async () => {
  if (!userInfo.value) return;
  try {
    await axios.put('/api/users/me', userInfo.value);
    alert('信息更新成功！');
  } catch (error) {
    console.error('保存失败:', error);
    alert('保存失败，请重试。');
  }
};

// 上传头像
const uploadAvatar = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files?.[0];
  if (!file) return;

  const formData = new FormData();
  formData.append('avatar', file);

  try {
    const response = await axios.put('/api/users/me/avatar', formData, {
      headers: { 'Content-Type': 'multipart/form-data' },
    });
    avatarUrl.value = response.data.avatar || response.data.avatarUrl;
    uploadStatus.value = '上传成功';
  } catch (error) {
    console.error('上传失败:', error);
    uploadStatus.value = '上传失败，请重试。';
  }
};

// 根据等级显示权限说明
const permissionDescription = computed(() => {
  if (!userInfo.value) return ''
  switch (userInfo.value.level) {
    case 1:
      return '仅可评论'
    case 2:
      return '可以发布帖子，编辑已发布的帖子'
    case 3:
      return '允许上传头像'
    case 4:
      return 'Super User：可以删除任意用户的帖子'
    default:
      return '未知等级'
  }
})

onMounted(() => {
  fetchUserInfo()
})
</script>
<style scoped>
:deep(.profile-container) {
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
}
.auth-form {
  max-width: 100%;
  padding: 60px;
  background: white;
  border-radius: 20px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
  font-family: 'Segoe UI', sans-serif;
}

.auth-form h3 {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 28px;
}
.profile-container {
  max-width: 960px;
  margin: 60px auto;
  padding: 60px;
  background: linear-gradient(135deg, #f8f9fa, #e9ecef);
  border-radius: 20px;
  box-shadow: 0 12px 30px rgba(0, 0, 0, 0.1);
  font-family: 'Segoe UI', sans-serif;
}

@media (max-width: 768px) {
  .profile-container {
    margin: 40px 20px;
    padding: 30px 20px;
  }
  
  .info-grid {
    grid-template-columns: 1fr;
  }
}

.profile-card {
  background: white;
  border-radius: 16px;
  padding: 30px;
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.05);
  transition: all 0.3s ease;
}

.profile-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 12px 24px rgba(0, 0, 0, 0.1);
}

.profile-title {
  text-align: center;
  color: #2c3e50;
  margin-bottom: 30px;
  font-size: 24px;
}

.avatar-section {
  margin-bottom: 30px;
}

.avatar-img {
  width: 120px;
  height: 120px;
  object-fit: cover;
  border-radius: 50%;
  border: 4px solid #409eff;
  transition: transform 0.3s ease;
}

.avatar-img:hover {
  transform: scale(1.1);
}

.avatar-input {
  display: none;
}

.upload-status {
  margin-top: 10px;
  font-size: 14px;
  color: green;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(220px, 1fr));
  gap: 15px;
  margin-bottom: 30px;
}

.info-item {
  display: flex;
  flex-direction: column;
  font-size: 15px;
  color: #333;
}

.info-item label {
  font-weight: bold;
  margin-bottom: 5px;
}

.level-tag {
  background-color: #409EFF;
  color: white;
  padding: 5px 10px;
  border-radius: 20px;
  font-size: 13px;
  align-self: flex-start;
}

.permission-desc {
  color: #7f8c8d;
  font-style: italic;
}

.edit-form {
  margin-bottom: 30px;
}

.submit-button {
  margin-top: 10px;
  font-size: 16px;
  border-radius: 8px;
  background: linear-gradient(to right, #4f46e5, #6d28d9);
  border: none;
  transition: background-color 0.3s ease;
}

.submit-button:hover {
  background: linear-gradient(to right, #3b34d1, #5a24c2);
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.logout-btn {
  text-align: center;
}
</style>